package com.franklin.ideaplugin.mybatisrunner.ui;

import com.franklin.ideaplugin.mybatisrunner.event.SqlEventFactory;
import com.franklin.ideaplugin.mybatisrunner.event.events.MybatisPsiElementRefreshEvent;
import com.franklin.ideaplugin.mybatisrunner.psi.MybatisPsiElement;
import com.google.common.collect.Maps;
import com.intellij.openapi.project.Project;

import java.util.Map;
import java.util.Optional;

/**
 * @author Ye Junhui
 * @since 2024/3/4
 */
public class SqlRunnerFormFactory {

    private final Project project;

    /**
     * 表单缓存
     */
    private final Map<String,SqlRunnerForm> formMap = Maps.newHashMap();

    public SqlRunnerFormFactory(Project project) {
        this.project = project;
    }

    public static SqlRunnerFormFactory getInstance(Project project){
        return project.getService(SqlRunnerFormFactory.class);
    }

    public synchronized void showSqlRunnerForm(MybatisPsiElement mybatisPsiElement){
        SqlRunnerForm form = formMap.computeIfAbsent(mybatisPsiElement.buildKey(), key -> {
            SqlRunnerForm sqlRunnerForm = new SqlRunnerForm(mybatisPsiElement);
            sqlRunnerForm.initParamPanel();
            return sqlRunnerForm;
        });
        form.showForm();

        Optional.ofNullable(formMap.get(mybatisPsiElement.buildKey()))
                .ifPresentOrElse(
                        existForm -> {
                            SqlEventFactory.getSqlMulticaster(mybatisPsiElement)
                                    .publishEvent(new MybatisPsiElementRefreshEvent(mybatisPsiElement));
                            existForm.showForm();
                        },
                        () -> showNewForm(mybatisPsiElement)
                );
    }

    /**
     * 展示新表单
     * @param mybatisPsiElement
     */
    private void showNewForm(MybatisPsiElement mybatisPsiElement){
        SqlRunnerForm sqlRunnerForm = new SqlRunnerForm(mybatisPsiElement);
        sqlRunnerForm.initParamPanel();
        sqlRunnerForm.showForm();
        formMap.put(mybatisPsiElement.buildKey(), sqlRunnerForm);
    }

    /**
     * 移除窗口
     * @param mybatisPsiElement
     */
    public static void removeForm(MybatisPsiElement mybatisPsiElement){
        getInstance(mybatisPsiElement.getProject()).formMap.remove(mybatisPsiElement.buildKey());
    }
}
